/**
 * Created by Deng on 17/8/10.
 */
const focus = Vue.directive('focus', {
    inserted: function (el) {
        // 获取焦点
        el.focus();
    }
})


const title = Vue.directive('title', {
    componentUpdated: function (el, binding) {

        document.title = el.innerText
        el.remove()
    }
})

const crop = Vue.directive('crop', {
    bind: function (el, binding, vnode) {

        let maskHide = function () {
            binding.value.loadingState.loading = false;
        }

        var crop = new Crop(el, {
            cropWidth: binding.value.data.pic_width,
            cropHeight: binding.value.data.pic_height,
            quality: 70
        });
        crop.on('error', function (code, msg) {
            maskHide();
            Vue.$alert.show({content: msg});
        }).on('crop', function (file, fileName, _file) {

            binding.value.data.field_result = {
                src: file,
                path: null,
                ysrc: null,
                ypath: null
            };
            //  获取压缩原图
            lrz(_file).then(function (rst) {
                // 上传裁剪图
                vnode.context.$http.post('http://sif-voteproxy.heikuai.com:8101/votepoxyif/file/save_file!save.action', {
                    filestr: rst.base64.substring(rst.base64.indexOf(',') + 1),
                    filename: fileName
                }, {emulateJSON: true}).then(function (res) {
                    maskHide();
                    if (res.body.code === 0) {
                        binding.value.data.field_result.base64 = rst.base64;
                        binding.value.data.field_result.path = res.body.result;
                    } else {
                        Vue.$alert.show({content: "上传图片失败"});
                    }
                }).catch(function (msg) {
                    maskHide();
                    Vue.$alert.show({content: "网络连接中断，请稍后重试"});

                });
            }).catch(function (err) {
                maskHide();
                // 处理失败会执行
                Vue.$alert.show({content: "压缩图片失败，请稍后重试"});
            });
        }).on('cancel', function () {
            maskHide();
        });
    }
})

export {title, focus, crop};